package com.example.discover.view

import android.annotation.SuppressLint
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.text.isDigitsOnly
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.featuresdk.model.Book
import com.example.discover.viewmodel.BookViewModel

@Composable
fun BookScreen(bookViewModel: BookViewModel = hiltViewModel()){

    /** observeAsState()
     * Starts observing this LiveData and represents its values via State.
     *
     * Every time there would be new value posted into the LiveData the returned State will be updated
     * causing recomposition of every State.value usage.
     *
     * The inner observer will automatically be removed when this composable disposes
     * or the current LifecycleOwner moves to the Lifecycle.State.DESTROYED state.
     */
    val books by bookViewModel.books.observeAsState(emptyList<Book>())
    //val totalSize by bookViewModel.totalSize.observeAsState("")
    //val totalPrice by bookViewModel.totalPrice.observeAsState("")
    //val book by bookViewModel.book.observeAsState(Book("","",""))


    Column() {

        BookSummary(books)

        Spacer(Modifier.height(8.dp))

        BookList(books)

        Spacer(Modifier.height(8.dp))

        if(books.isEmpty()) {
            BookForm(bookViewModel = bookViewModel)
        } else {
            BookForm(books.last(), bookViewModel)
        }
    }
}

@Composable
fun BookSummary(books: List<Book>){

    var totalPrice = 0
    books.forEach {
        if (it.price.isDigitsOnly()) {
            totalPrice += it.price.toInt()
        }
    }
    Row(modifier = Modifier.padding(all = 8.dp)) {
        Text(text = "Total Count:")

        Spacer(modifier = Modifier.width(20.dp))

        Text(text = "${books.size}")

        Spacer(modifier = Modifier.width(60.dp))

        Text(text = "Total Price:")

        Spacer(modifier = Modifier.width(20.dp))

        Text(text = "$totalPrice")
    }
}

@Preview
@Composable
fun PreviewBookSummary(){
    val books = listOf(Book("A2021","Android","100"), Book("B1234","Java","120"))
    BookSummary(books)
}

@SuppressLint("UnrememberedMutableState")
@Composable
fun BookForm(book: Book = Book("","",""), bookViewModel: BookViewModel){

    Column() {

        Row (modifier = Modifier.padding(all = 8.dp)){

            Button(onClick = {
                bookViewModel.add(book)
            }) {
                Text("Add")
            }

            Spacer(modifier = Modifier.width(20.dp))

            Button(onClick = {
                bookViewModel.update(book)
            }) {
                Text("Update")
            }

            Spacer(modifier = Modifier.width(20.dp))

            Button(onClick = {
                bookViewModel.remove(book.isbn)
            }) {
                Text("Remove")
            }
        }

        BookTextField("ISBN",mutableStateOf(book.isbn), KeyboardType.Ascii, _onValueChange = {book.isbn = it })

        Spacer(modifier = Modifier.height(5.dp))

        BookTextField("Name",mutableStateOf(book.name), _onValueChange = {book.name = it })

        Spacer(modifier = Modifier.height(5.dp))

        BookTextField("Price",mutableStateOf(book.price), KeyboardType.Number, _onValueChange = {book.price = it })

//        Spacer(modifier = Modifier.height(5.dp))
//
//        BookTextField("Date",mutableStateOf(book.date), KeyboardType.Number, _onValueChange = {book.date = it })
    }
}

@Composable
fun BookList(books:List<Book>){

    Text("Book List:")

    LazyColumn(Modifier.padding(8.dp, 16.dp, 0.dp, 0.dp)) {
        items(books) { book ->
            Text("${book.isbn}  ${book.name}  ${book.price}")
        }
    }
}


@Composable
fun BookTextField(label:String, fieldValue: MutableState<String>, keyboardType:KeyboardType = KeyboardType.Text,  _onValueChange: (String) -> Unit){

    Row {
        Text(
            text = label, textAlign = TextAlign.Left, modifier = Modifier
                .width(60.dp)
                .padding(8.dp, 16.dp, 0.dp, 0.dp)
        )

        Spacer(modifier = Modifier.width(10.dp))

        TextField(
            value = fieldValue.value,
            onValueChange = {
                fieldValue.value = it
                _onValueChange(it)
            },
            keyboardOptions = KeyboardOptions(keyboardType = keyboardType),
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.White,
                cursorColor = Color.Black
            )
        )
    }
}